import { login, logout, getInfo, authCode } from '@/api/user'
import { asyncRoutes, constantRoutes } from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: [],
    // 测试地址
    updateURL: process.env.VUE_APP_BASE_API, // 文件上传链接
    imgURL: process.env.VUE_APP_BASE_API // 图片链接
  }
}

const state = getDefaultState()

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTESMENU: (state, routemenu) => {
    state.routemenu = routemenu
  },
  SET_ROUTES: (state, routes) => {
    state.routes = routes
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: account.trim(), password: password })
        .then(response => {
          const { data } = response
          if (data.token) {
            // commit('SET_MENUS', data.menu)
            commit('SET_TOKEN', data.token)
            localStorage.setItem('navMenu', JSON.stringify(data.menu))
            setToken(data.token)
          }

          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  authCode({ commit }, userInfo) {
    const { phone, code } = userInfo
    return new Promise((resolve, reject) => {
      authCode({ phone: phone, code: code })
        .then(response => {
          const { data } = response
          // commit('SET_MENUS', data.menu)
          commit('SET_TOKEN', data.token)
          localStorage.setItem('navMenu', JSON.stringify(data.menu))
          setToken(data.token)
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // user logout
  logout({ commit }) {
    // commit('DEL_TOKEN')
    resetRouter()
    removeToken()
    router.push({
      path: '/login',
      query: {
        redirect: '/'
      }
    })
  },
  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },
  generateRoutes({ commit }, roles) {
    return new Promise(resolve => {
      // let accessedRoutes
      getInfo().then(res => {
        var menuArr = res.data
        commit('SET_ROUTESMENU', menuArr)
        commit('SET_ROUTES', constantRoutes)
        resolve(res)
      })
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, {
      root: true
    })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
